package org.xfy.org.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xfy.base.util.AjaxResult;
import org.xfy.base.util.FastDfsUtils;

import java.io.IOException;

/**
 * 上传
 * 下载 = 不需要
 * 查看 = 路径
 * 删除
 * 更新 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //@RequestPart对复杂表单项的处理，默认name="file",与上传文件的name属性值一致
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){

        try {
            System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            String filePath =  FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败!"+e.getMessage());
        }
    }
    /**
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     *     //模拟前端发送请求调用该接口1：Delete http://localhost:8080/fastDfs//group1/M00/04/72/CgAIC2QetIuAVFPIAAgFDuhQH8Q183.gif - 不用
    //模拟前端发送请求调用该接口2：Delete http://localhost:8080/fastDfs?path=/group1/M00/04/72/CgAIC2QetIuAVFPIAAgFDuhQH8Q183.gif - 采用
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
        String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
        String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
        FastDfsUtils.delete(groupName, remotePath);
        return  AjaxResult.me();
    }
}